<!DOCTYPE html>
<html>

<head>
    <title>ChatChain 可视化工具</title>
    <link rel="stylesheet" href="js/materialize.min.css">
    <style>
        body {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background-image: url('figures/chat_chain_bg.jpg');
            background-repeat: no-repeat;
            background-size: cover;
            background-attachment: fixed;
            font-family: sans-serif;
            font-size: 16px;
            padding: 20px;
            box-sizing: border-box;
        }

        .container {
            background-color: rgba(255, 255, 255, 0.9);
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
            text-align: center;
            max-width: 90%;
        }

        h2 {
            font-size: 2.5em;
            color: #333;
            margin-bottom: 20px;
        }

        p {
            font-size: 1.1em;
            color: #555;
            margin-bottom: 25px;
        }

        input[type="file"],
        button {
            background-color: #007bff;
            color: white;
            padding: 12px 25px;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 1em;
            margin: 10px 5px;
            transition: background-color 0.3s ease, transform 0.2s ease;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.15);
        }

        input[type="file"]::-webkit-file-upload-button {
            background-color: transparent;
            color: white;
            border: none;
            padding: 0;
            font-size: 1em;
        }
        
        input[type="file"] {
            min-width: 250px;
        }

        button:hover,
        input[type="file"]:hover {
            background-color: #0056b3;
            transform: translateY(-2px);
        }

        #visualization {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            overflow-y: auto;
            width: 100%;
            max-width: 100%;
            max-height: 1000px;
            margin: 20px auto;
            padding: 10px;
            box-sizing: border-box;
        }

        .card {
            margin-right: 10px;
            display: inline-block;
            min-width: 300px;
            vertical-align: top;
            font-size: 14px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border-radius: 8px;
        }

        .simple-phase {
            background-color: #E8ECEB;
        }

        .composed-phase {
            background-color: #A3B4C8;
        }

        .nested-simple-phase {
            background-color: #E3DCD2;
        }

        .card-content {
            padding: 10px;
        }

        .card-content pre { /* 用于预格式化文本（JSON内容）的样式 */
            white-space: pre-wrap;       /* 允许换行，但保留格式 */
            word-wrap: break-word;       /* 断开长单词以防止溢出 */
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 7;      /* 显示最多7行 */
            -webkit-box-orient: vertical;
            max-height: 120px;          /* 为不支持line-clamp的浏览器提供回退，根据需要调整 */
                                        /* (7行 * 约1.2em行高 + padding) */
            font-size: 0.9em;         /* 略小的字体以适应JSON块 */
            background-color: #f9f9f9; /* 浅色背景用于JSON块 */
            padding: 8px;
            border-radius: 4px;
            margin-top: 8px;
        }
    </style>
</head>

<body>
    <div class="container">
        <h2>ChatChain 可视化工具</h2>
        <p>请选择 CompanyConfig/ 目录下的 ChatChainConfig.json 文件进行可视化</p>
        <input type="file" id="fileInput" accept=".json">
        <button id="exportButton">导出为图片</button>
        <div id="visualization"></div>
    </div>

    <script src="js/html2canvas.min.js"></script>
    <script>
        document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
        document.getElementById('exportButton').addEventListener('click', exportAsImage, false);

        function handleFileSelect(event) {
            const file = event.target.files[0];
            if (!file) return;

            const reader = new FileReader();
            reader.onload = function(event) {
                try {
                    const jsonContent = JSON.parse(event.target.result);
                    visualizeChain(jsonContent.chain);
                } catch (error) {
                    alert('解析JSON文件时出错。');
                }
            };
            reader.readAsText(file);
        }

        function createCard(element) {
            const card = document.createElement('div');
            card.className = 'card';

            const cardContent = document.createElement('div');
            cardContent.className = 'card-content';

            if (element.phaseType === "ComposedPhase") {
                delete element.Composition;
            }

            const phase = document.createElement('span');
            phase.innerHTML = `<strong>阶段名称: </strong>${element.phase || '无阶段名称'}`;
            const phaseType = document.createElement('p');
            phaseType.innerHTML = `<strong>阶段类型: </strong>${element.phaseType || '无阶段类型'}`;
            delete element.phase;
            delete element.phaseType;
            const jsonContent = document.createElement('pre');
            jsonContent.innerText = JSON.stringify(element, null, 2);
            cardContent.appendChild(phase);
            cardContent.appendChild(phaseType);
            cardContent.appendChild(jsonContent);
            card.appendChild(cardContent);

            return card;
        }

        function visualizeChain(chain) {
            const visualization = document.getElementById('visualization');
            visualization.innerHTML = '';

            chain.forEach(element => {
                if (element.phaseType === "ComposedPhase") {
                    const composition = element.Composition || [];
                    const card = createCard(element);

                    const nestedCards = composition.map(composedElement => {
                        return createCard(composedElement);
                    });

                    const nestedCardWrapper = document.createElement('div');
                    nestedCardWrapper.style.marginTop = '10px';

                    nestedCards.forEach(nestedCard => {
                        nestedCard.classList.add('nested-simple-phase');
                        nestedCardWrapper.appendChild(nestedCard);
                    });

                    card.classList.add('composed-phase');
                    card.appendChild(nestedCardWrapper);
                    visualization.appendChild(card);
                } else {
                    const card = createCard(element);
                    card.classList.add('simple-phase');
                    visualization.appendChild(card);
                }
            });
        }

        function exportAsImage() {
            const visualization = document.getElementById('visualization');
            const totalWidth = visualization.scrollWidth;
            const totalHeight = visualization.scrollHeight;

            console.log(totalWidth, totalHeight)

            const canvas = document.createElement('canvas');
            canvas.width = totalWidth + 100;
            canvas.height = totalHeight + 100;

            html2canvas(visualization, { scrollX: 0, scrollY: 0, width: totalWidth, height: totalHeight, useCORS: true }).then(canvas => {
                const link = document.createElement('a');
                link.href = canvas.toDataURL();
                link.download = 'ChatChain_可视化.png';
                link.click();
            });
        }
    </script>
</body>

</html>